package com.linran.javaweb.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linran.javaweb.controller.param.UserCreateGroup;
import com.linran.javaweb.controller.param.UserCreateParam;
import com.linran.javaweb.vo.User;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

@RestController
@RequestMapping("user")
public class UserController {

    @GetMapping("info")
    public Object userInfo(@RequestParam("name") String name) throws JsonProcessingException {
        User user = new User();
        user.setAge(18);
        user.setBirth(new Date());
        user.setFirstName("lin");
        user.setName("name");
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(user);
    }

    /*公共字段-批量校验*/
    public void syncValidate(List<UserCreateParam> list) {
        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        list.stream()
                .map(param -> {
                    Set<ConstraintViolation<UserCreateParam>> set = validator.validate(param, UserCreateGroup.class);
                    if (CollectionUtils.isEmpty(set)) {
                        // 校验通过

                    } else {
                        // 校验失败
                        List<String> messages = set.stream()
                                .map(violation -> (violation.getMessage()
                                        .replace("{", "")
                                        .replace("}", "")))
                                .collect(toList());
                    }
                    return "test";
                })
                .collect(Collectors.toList());
    }
}
